/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.diegohp.swing;

import java.util.ArrayList;
import java.util.List;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 *
 * @author Diego
 */
public class CustomerTableModelJDialog extends javax.swing.JDialog {

    /**
     * Creates new form CustomerTableModelJDialog
     */
    public CustomerTableModelJDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        SwingHelper.centerWindow(this);
        
        this.customersListTableModel = new ListTableModel<Customer>() {

            @Override
            public Object getValueAt(int row, int col) {
                Customer customer = this.objects.get(row);
                if (col == 0) {
                    return customer.getId();
                }
                if (col == 1) {
                    return customer.getName();
                }
                if (col == 2) {
                    return customer.getViews();
                }
                return customer.getId() + " -> " + customer.getName();
            }
        };
        
        List<String> columnsNames = new ArrayList<String>();
        columnsNames.add("Id");
        columnsNames.add("Name");
        columnsNames.add("Views");
        this.customersListTableModel.setColumnNames(columnsNames);
        
        
        this.jTableCustomers.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent lse) {
                if(!lse.getValueIsAdjusting()){
                    ListSelectionModel model = jTableCustomers.getSelectionModel();
                    if(model.getLeadSelectionIndex() >= 0){
                        customerSelected = ((ListTableModel<Customer>)jTableCustomers.getModel()).getObjectAt(model.getLeadSelectionIndex());
                        customerSelected.setViews(customerSelected.getViews() + 1);
                        customersListTableModel.fireTableDataChanged();
                        SwingHelper.showInformationMessage("Clicked on a Customer", "Customer's Id is " + customerSelected.getId() + " and name is " + customerSelected.getName());
                    }
                }
            }
        });
        
        jTableCustomers.setModel(this.customersListTableModel);
        
        List<Customer> customers = new ArrayList<Customer>();
        
        Customer c1 = new Customer();
        c1.setId(123456789L);
        c1.setName("Harry Mason");
        c1.setViews(0);
        
        Customer c2 = new Customer();
        c2.setId(987654321L);
        c2.setName("James Sunderland");
        c2.setViews(0);
        
        customers.add(c1);
        customers.add(c2);
        
        this.customersListTableModel.addObjectList(customers);
        this.customersListTableModel.fireTableDataChanged();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTableCustomers = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jTableCustomers.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jTableCustomers.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTableCustomers.setIntercellSpacing(new java.awt.Dimension(4, 4));
        jScrollPane1.setViewportView(jTableCustomers);

        jLabel1.setText("Click on any of the names: (close this window when finished)");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 283, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CustomerTableModelJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CustomerTableModelJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CustomerTableModelJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CustomerTableModelJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                CustomerTableModelJDialog dialog = new CustomerTableModelJDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableCustomers;
    // End of variables declaration//GEN-END:variables

    private ListTableModel<Customer> customersListTableModel;
    private Customer customerSelected;
}
